#!/bin/bash

#  load KUBE_FLAG variable
KUBE_VARS_FILE=/opt/asf/.kube_vars
. $KUBE_VARS_FILE


# echo "Kuberenete FLAG : $KUBE_FLAG" >> /var/log/eyewitness.log

if [ $KUBE_FLAG = "TRUE" ]
then
    #echo "Using Kuberenetes" >> /var/log/eyewitness.log
    # Get current context
    KUBE_CONTEXT=$(cat ~/.kube/config | grep "current-context:" | sed "s/current-context: //")
   
    #echo "Kuberenetes context:  $KUBE_CONTEXT" >> /var/log/eyewitness.log
    if [ -z ${KUBE_CONTEXT} ]
    then
        echo "Empty context"
        KUBE_FLAG=FALSE
    else
	export KUBECONFIG=$KUBE_CONFIG

	USE_CONTEXT=$(kubectl config use-context $KUBE_CONTEXT 2>&1)
#	echo "Kuberenetes use context :  $USE_CONTEXT" >> /var/log/eyewitness.log

	# Check if context is correct or not
	GET_CONTEXT=$(kubectl config current-context 2>&1)
#	echo "Kuberenetes get context now :  $GET_CONTEXT" >> /var/log/eyewitness.log

        if [ $KUBE_CONTEXT != $GET_CONTEXT ]
        then
            KUBE_FLAG=FALSE
        fi
    fi
fi

if test "f$1" "=" "f"
then 
    echo "Error, please specify a JobID"
    exit 1
fi
. /opt/asf/tools/scripts/arguments eyewitness $1
DATE_STAMP=`date +"%Y%m%d%H%M%S"`
JOB_FOLDERS="/home/asf/jobs"
JOB_FOLDER="$JOB_FOLDERS/$1"
JOB_OUTPUT_FOLDER="$JOB_FOLDER/$DATE_STAMP"
TERM="xterm"
if ! test -e "$JOB_FOLDER"
then 
    echo "Error, JobID $1 is invalid"
    exit 1
fi
if test -e "JOB_FOLDER/.lock"
then 
	echo "Error, process is already running"
	exit 1
fi
echo > "$JOB_FOLDER/.lock"
cd /opt/asf/frontend/asfui
. bin/activate
python3 manage.py remaster_input --input JobID:$1 --parser url --output "$JOB_FOLDER/app.input"
mkdir -p $JOB_OUTPUT_FOLDER
for mode in input asf
do cp -v "$JOB_FOLDER/app.$mode" "$JOB_OUTPUT_FOLDER/app.$mode"
done

if [ $KUBE_FLAG = "TRUE" ]
then
    # TODO: get namespace as input from user input
    #echo "Executing kubectl" >> /var/log/eyewitness.log
    # Apply deployment yaml to k8s cluster
    cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: eyewitness-$DATE_STAMP
spec:
  securityContext:
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
  volumes:
  - name: tmp-vol
    emptyDir: {}
  - name: eyewitness-vol
    emptyDir: {}
  - name: eye-py-vol
    emptyDir: {}
  containers:
    - name: eyewitness
      image: m4ch1n3s/eyewitness
      volumeMounts:
        - name: tmp-vol
          mountPath: /tmp/EyeWitness
        - name: eye-py-vol
          mountPath: EyeWitness/Python
      resources:
        requests:
          memory: "1024Mi"
        limits:
          memory: "2048Mi"
      command: ["/bin/sh"]
      args: ["-c", "while true; do sleep 10;done"]
      securityContext:
        allowPrivilegeEscalation: false
EOF
    
    kubectl wait --for=condition=Ready pod/eyewitness-$DATE_STAMP
    echo "kubectl wait --for=condition=Ready pod/eyewitness-$DATE_STAMP"
    #echo "kubectl apply is success" >> /var/log/eyewitness.log
    # copy the app.input file to k8s tmp folder
    kubectl cp $JOB_FOLDER/app.input $NAMESPACE/eyewitness-$DATE_STAMP:/tmp
    
    #echo "kubectl copy is done" >> /var/log/eyewitness.log
    # run the Eyewitness command
    kubectl exec --stdin --tty eyewitness-$DATE_STAMP -- Python/EyeWitness.py --web -f /tmp/app.input --timeout 123 --results 300 -d /tmp/$DATE_STAMP --selenium-log-path /tmp/.geckodriver.log --no-prompt 2>&1 > app.log
    #echo "kubectl exec is completed" >> /var/log/eyewitness.log

    # copy the output back to jobs folder in ASF
    kubectl cp $NAMESPACE/eyewitness-$DATE_STAMP:/tmp/$DATE_STAMP $JOB_OUTPUT_FOLDER

    # delete the pod
    kubectl delete pod eyewitness-$DATE_STAMP
else
    #echo "executing docker" >> /var/log/eyewitness.log
    echo docker run --rm -v $JOB_OUTPUT_FOLDER/:/tmp/EyeWitness/ secsi/eyewitness --web --timeout 120 -f /tmp/EyeWitness/app.input --results 300 --no-prompt 2>&1 \> "$JOB_OUTPUT_FOLDER/app.log"
    docker run --rm -v $JOB_OUTPUT_FOLDER/:/tmp/EyeWitness/ secsi/eyewitness --web --timeout 120 -f /tmp/EyeWitness/app.input --results 300 --no-prompt 2>&1 > "$JOB_OUTPUT_FOLDER/app.log" &
fi

JOB_PID=$!
echo $JOB_PID>"$JOB_FOLDER/pid"
/opt/asf/redteam/eyewitness/extract_pics_mon.sh "$JOB_OUTPUT_FOLDER" "$JOB_FOLDER/pid" & 
wait $JOB_PID
/opt/asf/redteam/eyewitness/extract_pics.sh "$JOB_OUTPUT_FOLDER" 
rm -v "$JOB_FOLDER/pid"
rm -v "$JOB_FOLDER/.lock"